<?php

class image{
    
    /**
     *  Download images from remote server
     * @param type $inPath, any url
     * @param type $outPath, images/profile
     */
    function save_image($inPath,$outPath){
        $in  = fopen($inPath, "rb");
        $out = fopen($outPath, "wb");
        while ($chunk = fread($in,8192))
        {
            fwrite($out, $chunk, 8192);
        }
        fclose($in);
        fclose($out);
    }

     /**
     *  Download images from remote server using wget
     * @param type $inPath, any url
     * @param type $outPath, images/profile
     */
    function save_image_wget($inPath,$outPath){
        echo "wget -P$outPath $inPath";
        exec("wget -P$outPath $inPath");

    }

    /**
     * Image resize
     * @param int $width
     * @param int $height
     */
    function resize($file, $type, $pathname, $width = 180, $height =135){
        /* Get original image x y*/
        list($w, $h) = getimagesize($file);
        
        /* calculate new image size with ratio */
        $ratio = max($width/$w, $height/$h);
        $h = ceil($height / $ratio);
        $x = ($w - $width / $ratio) / 2;
        $w = ceil($width / $ratio);
        
        /* read binary data from image file */
        $imgString = file_get_contents($file);
        
        /* create image from string */
        $image = imagecreatefromstring($imgString);
        $tmp = imagecreatetruecolor($width, $height);
        imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
        
        /* Save image */
        switch ($type) {
            case 'image/jpeg':
                imagejpeg($tmp, $pathname, 100);
                break;
            case 'image/png':
                imagepng($tmp, $pathname, 0);
                break;
            case 'image/gif':
                imagegif($tmp, $pathname);
                break;
            default:
                exit;
                break;
        }
        
        imagedestroy($image);
        imagedestroy($tmp);
    }    
    
}
?>
